package T回溯;

import java.util.*;

/**
 * @author tmh
 * @date 2023/10/17 15:52
 * @description T_40组合总和II
 */
public class T_40组合总和II {
    List<List<Integer>> result = new LinkedList<>();
    LinkedList<Integer> path = new LinkedList<>();
    boolean[] used;

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        used = new boolean[candidates.length];
        Arrays.fill(used, false);
        //这里需要进行排序
        Arrays.sort(candidates);
        backTracking(candidates, target, 0);
        return result;
    }

    private void backTracking(int[] candidates, int target, int startIndex) {
        if (path.stream().mapToInt(i -> i).sum() > target) {
            return;
        }
        if (path.stream().mapToInt(i -> i).sum() == target) {
            result.add(new LinkedList<>(path));
            return;
        }
        for (int i = startIndex; i < candidates.length; i++) {
            //树层去重逻辑，使用used数组
            if (i > 0 && candidates[i] == candidates[i - 1] && used[i - 1]== false){
                continue;
            }
            path.add(candidates[i]);
            used[i]=true;
            backTracking(candidates, target, i + 1);
            path.removeLast();
            used[i]=false;
        }
    }

    public static void main(String[] args) {
        T_40组合总和II t = new T_40组合总和II();
        int[] array = {10, 1, 2, 7, 6, 1, 5};
        int target = 8;
        List<List<Integer>> list = t.combinationSum2(array, target);
        System.out.println(list);
    }

}
